package com.kly.manager.upload;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import com.kly.exception.BusinessException;
import com.kly.exception.ErrorCode;
import com.kly.exception.ThrowUtils;
import org.springframework.stereotype.Service;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.List;

/**
 * @author admin
 * @date 2025/3/5
 */
@Service
public class UrlPictureUpload extends PictureUploadTemplate {
    @Override
    protected File processFile(Object inputSource, File tempFile) {
        String fileUrl = (String) inputSource;
        HttpUtil.downloadFile(fileUrl, tempFile);
        return tempFile;
    }

    @Override
    protected String getOriginalName(Object inputSource) {
        String fileUrl = (String) inputSource;
        return FileUtil.mainName(fileUrl);
    }

    @Override
    protected void validatePictureInfo(Object inputSource) {
        String fileUrl = (String) inputSource;
//     1. 校验url
        ThrowUtils.throwIf(StrUtil.isBlank(fileUrl), ErrorCode.PARAMS_ERROR, "url不能为空");
        //     2. 校验url是否合法
        try {
            new URL(fileUrl);
        } catch (MalformedURLException e) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "url不合法");
        }
        // 校验域名
        ThrowUtils.throwIf(!fileUrl.startsWith("http://") && !fileUrl.startsWith("https://"), ErrorCode.PARAMS_ERROR, "url不合法");
        //     3. 校验文件是否存在
        HttpResponse response = HttpUtil.createRequest(Method.HEAD, fileUrl).execute();
        if(!response.isOk()) {
            response = HttpUtil.createRequest(Method.GET, fileUrl).execute();
            ThrowUtils.throwIf(!response.isOk(), ErrorCode.PARAMS_ERROR, "解析文件出错，图片不存在");
        }
        //     4. 校验文件是否是图片
        String header = response.header("Content-Type");
        final List<String> IMAGE_FORMATS = Arrays.asList("image/jpeg", "image/png", "image/gif", "image/jpg", "application/octet-stream", "application/xml");
        ThrowUtils.throwIf(!IMAGE_FORMATS.contains(header), ErrorCode.PARAMS_ERROR, "文件格式不正确");
        //     5, 校验文件大小
        String lengthStr = response.header("Content-Length");
        ThrowUtils.throwIf(StrUtil.isBlank(lengthStr), ErrorCode.PARAMS_ERROR, "文件大小不合适");
        long length = Long.parseLong(lengthStr);
        ThrowUtils.throwIf(length > 10 * ONE_M, ErrorCode.PARAMS_ERROR, "图片内容过大");
    }
}
